﻿Imports System.Data
Imports VSModel
Imports Cls_Common
Imports SecurityService
Imports System.IO

Partial Class Control_Raovat_List
    Inherits System.Web.UI.UserControl
    Dim level As String = -1
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)

#Region "Sub and Function"

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "duyjs", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "duyjs", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If
            getStatus()
            '      getStore()
            getMenu()
            BindToGrid()
            btnDelete.Attributes.Add("onclick", "return confirmMultiDelete('" & btnDelete.ClientID & "');")
        End If
    End Sub
    Protected Sub getMenu()
        ddlType.Items.Clear()
        ddlType.AppendDataBoundItems = True
        ddlType.Items.Insert(0, New ListItem("---Tất cả---", "-1"))
        Using data As New VSEntities
            Dim query As List(Of Category) = (From q In data.Categories Order By q.Sort Ascending Select q).ToList
            ddlType.DataValueField = "CatId"
            ddlType.DataTextField = "Title"
            If Not query Is Nothing Then
                RecursiveFillTree(query, 0)
            End If
        End Using
    End Sub
    Private Sub RecursiveFillTree(ByVal dtParent As List(Of Category), ByVal parentID As Integer)
        level += 1
        'on the each call level increment 1
        Dim appender As New StringBuilder()

        For j As Integer = 0 To level - 1

            appender.Append("&nbsp;&nbsp;&nbsp;&nbsp;")
        Next
        If level > 0 Then
            appender.Append("|__")
        End If

        Using data As New VSEntities
            Dim dv As List(Of Category) = (From q In data.Categories Where q.ParentId = parentID Select q).ToList
            Dim i As Integer
            If dv.Count > 0 Then
                For i = 0 To dv.Count - 1
                    Dim itm As New ListItem(Server.HtmlDecode(appender.ToString() + dv.Item(i).Title.ToString()), dv.Item(i).CatId.ToString())
                    ddlType.Items.Add(itm)
                    RecursiveFillTree(dtParent, Integer.Parse(dv.Item(i).CatId.ToString()))
                Next
            End If
        End Using
        level -= 1
        'on the each function end level will decrement by 1
    End Sub

    Protected Sub getStatus()
        ddlStatus.Items.Clear()
        ddlStatus.AppendDataBoundItems = True
        ddlStatus.Items.Add(New ListItem("---Chọn---", "-1"))
        Using data As New VSEntities
            Dim p = (From q In data.Status Select q.StatusId, q.Title).ToList
            ddlStatus.DataValueField = "StatusId"
            ddlStatus.DataTextField = "Title"
            ddlStatus.DataSource = p
            ddlStatus.DataBind()
            ddlStatus.SelectedValue = -1
        End Using

    End Sub
    Protected Sub getStore()
        ddlStore.Items.Clear()
        ddlStore.AppendDataBoundItems = True
        ddlStore.Items.Add(New ListItem("---Chọn---", "-1"))
        Using data As New VSEntities
            Dim p = (From q In data.Stores Select q.StoreId, q.Title).ToList
            ddlStore.DataValueField = "StoreId"
            ddlStore.DataTextField = "Title"
            ddlStore.DataSource = p
            ddlStore.DataBind()
            ddlStore.SelectedValue = -1
        End Using
    End Sub
    Private Sub BindToGrid(Optional ByVal iPage As Integer = 1, _
                           Optional ByVal strTitle As String = "", _
                           Optional ByVal intCateId As Integer = -1, _
                           Optional ByVal dtmCreatedFrom As Date = #1/1/1900#, _
                           Optional ByVal dtmCreatedTo As Date = #12/31/3999#, _
                           Optional ByVal strCreator As String = "", _
                           Optional ByVal intIsSellOff As Integer = -1, _
                           Optional ByVal intIsHot As Integer = -1, _
                           Optional ByVal intStatusId As Integer = -1, _
                           Optional ByVal dtmPublishedDateFrom As Date = #1/1/1900#, _
                           Optional ByVal dtmPublishedDateTo As Date = #12/31/3999#)
        Using data As New VSEntities
            Dim arrSearch() As String = {iPage.ToString, strTitle.ToString, intCateId.ToString, dtmCreatedFrom.ToString, dtmCreatedTo.ToString, strCreator, intIsSellOff.ToString, intIsHot.ToString, intStatusId.ToString, dtmPublishedDateFrom.ToString, dtmPublishedDateTo.ToString}
            ViewState("search") = arrSearch
            'So ban ghi muon the hien tren trang
            Dim intPag_Size As Int32 = drpPage_Size.SelectedValue
            Dim p As List(Of uspRaovatSelectAll_Result) = data.uspRaovatSelectAll(strTitle, _
                                                                                  intCateId, _
                                                                                  dtmCreatedFrom, _
                                                                                  dtmCreatedTo, _
                                                                                   strCreator, _
                                                                                   intIsSellOff, _
                                                                                   intIsHot, _
                                                                                   intStatusId, _
                                                                                   dtmPublishedDateFrom, _
                                                                                   dtmPublishedDateTo, _
                                                                                   iPage, intPag_Size).ToList

            'Dim p = (From q In data.RaoVats Order By q.RaovatId Descending Select New With {q.RaovatId, q.Title, q.PublishedDate, q.Created, .Creator = q.User.UserName, q.Modified, .Modifier = q.User.UserName, .StatusName = q.Status.Title}).Skip((iPage - 1) * intPag_Size).Take(intPag_Size).ToList
            Dim strKey_Name() As String = {"RaovatId", "Title"}
            'Tong so ban ghi
            If p.Count > 0 Then
                hidCount.Value = p.FirstOrDefault.Total()

            Else
                hidCount.Value = 0
                With rptPage
                    .DataSource = Nothing
                    .DataBind()
                End With
            End If

            Create_Pager(hidCount.Value, iPage, intPag_Size, 10)
            With grdShow
                .DataKeyNames = strKey_Name
                .DataSource = p
                .DataBind()
            End With
            lblTotal.Text = "Hiển thị " + (((iPage - 1) * intPag_Size) + 1).ToString + " đến " + (((iPage - 1) * intPag_Size) + grdShow.Rows.Count).ToString + " trong tổng số " + hidCount.Value.ToString + " bản ghi."
        End Using
    End Sub
    Sub Create_Pager(ByVal Total_Record As Integer, ByVal Page_Index As Integer, ByVal Page_Size As Integer, ByVal Page2Show As Integer)
        Dim TotalPage As Integer = IIf((Total_Record Mod Page_Size) = 0, Total_Record / Page_Size, Total_Record \ Page_Size + 1)
        'lu lai tong so ban ghi
        hidIndex_page.Value = TotalPage
        'gan lai curPage de set active
        hidCur_Page.Value = Page_Index
        'generate ra left page
        Dim cPageGenerate_left As IEnumerable(Of Integer)
        If Page_Index <= Page2Show Then
            cPageGenerate_left = Enumerable.Range(1, Page_Index)
        Else
            cPageGenerate_left = Enumerable.Range(Page_Index - Page2Show, Page2Show)
        End If
        'generate ra right page
        Dim cPageGenerate_Right As IEnumerable(Of Integer)
        If Page_Index + Page2Show <= TotalPage Then
            cPageGenerate_Right = Enumerable.Range(Page_Index, Page2Show + 1)
        Else
            cPageGenerate_Right = Enumerable.Range(Page_Index, TotalPage - Page_Index + 1)
        End If
        'union 2 range va bind to Grid
        With rptPage
            .DataSource = cPageGenerate_left.Union(cPageGenerate_Right)
            .DataBind()
        End With
    End Sub
    Protected Sub rptPage_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptPage.ItemDataBound
        Dim lnkTitle As LinkButton
        lnkTitle = e.Item.FindControl("lnkTitle")
        Dim ScriptManager As System.Web.UI.ScriptManager = System.Web.UI.ScriptManager.GetCurrent(Me.Page)
        ScriptManager.RegisterAsyncPostBackControl(lnkTitle)
        If e.Item.DataItem = hidCur_Page.Value Then
            lnkTitle.Text = "<span class='current'>" & e.Item.DataItem & "</span>"
        Else
            lnkTitle.Text = "<span>" & e.Item.DataItem & "</span>"
        End If
        lnkTitle.ToolTip = e.Item.DataItem
    End Sub
    Protected Sub lnkTitle_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim lnkTile As LinkButton = CType(sender, LinkButton)
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(CInt(lnkTile.ToolTip), arrSearch(1).ToString, CInt(arrSearch(2).ToString), arrSearch(3), arrSearch(4), arrSearch(5).ToString, CInt(arrSearch(6).ToString), CInt(arrSearch(7).ToString), CInt(arrSearch(8).ToString), arrSearch(9), arrSearch(10))

        lnkLast.Enabled = True
        lnkFirst.Enabled = True
        If CInt(lnkTile.ToolTip) = hidIndex_page.Value Then
            lnkLast.Enabled = False
        ElseIf CInt(lnkTile.ToolTip) = 1 Then
            lnkFirst.Enabled = False
        End If
    End Sub
    Protected Sub lnkFirst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkFirst.Click
        If hidCur_Page.Value > 1 Then
            hidCur_Page.Value = hidCur_Page.Value - 1
        End If
        BindToGrid(hidCur_Page.Value)
    End Sub
    Protected Sub lnkLast_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkLast.Click
        hidCur_Page.Value = hidCur_Page.Value + 1
        BindToGrid(hidCur_Page.Value)
    End Sub
#End Region

#Region "Event for control"

    Protected Sub lnkbtnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim intId As Integer
        Dim strLogName As String = ""
        Using data As New VSEntities
            intId = grdShow.DataKeys(hidID.Value)("RaovatId").ToString

            Dim l = (From d In data.ThongSoCoBans Where d.RaoVatId = intId Select d).FirstOrDefault
            If Not l Is Nothing Then
                data.ThongSoCoBans.DeleteObject(l)
            End If

            Dim g = (From k In data.ThongSoKyThuats Where k.RaoVatId = intId Select k).FirstOrDefault
            If Not g Is Nothing Then
                data.ThongSoKyThuats.DeleteObject(g)
            End If
            Dim u = (From r In data.TienNghis Where r.RoaVatId = intId Select r).FirstOrDefault
            If Not u Is Nothing Then
                data.TienNghis.DeleteObject(u)
            End If
            Dim t = (From c In data.AnToans Where c.RaoVatId = intId Select c).FirstOrDefault
            If Not t Is Nothing Then
                data.AnToans.DeleteObject(t)
            End If

            Dim a = (From b In data.RaovaImages Where b.RaoVatId = intId Select b).ToList
            For Each abc In a
                Dim DelPath = Server.MapPath("~/Uploads") & (abc.ImageURL.Replace("http://otosaithanh.com/Uploads", "").Replace(MainDomain & "Uploads", ""))
                DeleteFileRaoVat(DelPath)
                data.RaovaImages.DeleteObject(abc)
            Next

            Dim j = (From s In data.TinNhans Where s.RaoVatId = intId Select s).ToList
            For Each o In j
                data.TinNhans.DeleteObject(o)
            Next

            Dim w = (From z In data.TinDaLuus Where z.RaoVatID = intId Select z).ToList
            For Each m In w
                data.TinDaLuus.DeleteObject(m)
            Next

            data.SaveChanges()

            ' xoa ben auto
            Dim auto = (From r In data.AutoUpdates Where r.RaoVatId = intId Select r).ToList
            For Each y In auto
                data.AutoUpdates.DeleteObject(y)
            Next
            data.SaveChanges()

            Dim q = (From p In data.RaoVats Where p.RaovatId = intId Select p).FirstOrDefault
            Try
                'delete image
                Dim DelPath = Server.MapPath("~/Uploads") & (q.ImagePreview.Replace("http://otosaithanh.com/Uploads", "").Replace(MainDomain & "Uploads", ""))
                DeleteFileRaoVat(DelPath)

                data.RaoVats.DeleteObject(q)
                data.SaveChanges()
                Insert_App_Log("Insert Rao vat:" & txtTitle.Text.Trim & "", Function_Name.Raovat, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                Excute_Javascript("Alertbox('Xóa dữ liệu thành công.');", Me.Page, True)
            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
            End Try
        End Using
        BindToGrid()
    End Sub
    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        Dim intId As Integer = 0
        Dim intCount As Integer
        Dim intTotal As Integer
        Using data As New VSEntities
            Try
                For Each item As GridViewRow In grdShow.Rows
                    Dim chkItem As New CheckBox
                    chkItem = CType(item.FindControl("chkItem"), CheckBox)
                    If chkItem.Checked Then
                        intTotal += 1
                        intId = grdShow.DataKeys(item.RowIndex)("RaovatId").ToString

                        Dim l = (From d In data.ThongSoCoBans Where d.RaoVatId = intId Select d).FirstOrDefault
                        If Not l Is Nothing Then
                            data.ThongSoCoBans.DeleteObject(l)
                        End If
                        Dim g = (From k In data.ThongSoKyThuats Where k.RaoVatId = intId Select k).FirstOrDefault
                        If Not g Is Nothing Then
                            data.ThongSoKyThuats.DeleteObject(g)
                        End If
                        Dim u = (From r In data.TienNghis Where r.RoaVatId = intId Select r).FirstOrDefault
                        If Not u Is Nothing Then
                            data.TienNghis.DeleteObject(u)
                        End If
                        Dim t = (From c In data.AnToans Where c.RaoVatId = intId Select c).FirstOrDefault
                        If Not t Is Nothing Then
                            data.AnToans.DeleteObject(t)
                        End If
                        ' xoa ben auto
                        Dim auto = (From r In data.AutoUpdates Where r.RaoVatId = intId Select r).ToList
                        For Each y In auto
                            data.AutoUpdates.DeleteObject(y)
                        Next
                        data.SaveChanges()


                        Dim a = (From b In data.RaovaImages Where b.RaoVatId = intId Select b).ToList
                        For Each abc In a
                            'xoa file
                            'delete system
                            Dim DelPath = Server.MapPath("~/Uploads") & (abc.ImageURL.Replace("http://otosaithanh.com/Uploads", "").Replace(MainDomain & "Uploads", ""))
                            DeleteFileRaoVat(DelPath)
                            data.RaovaImages.DeleteObject(abc)
                        Next

                        Dim j = (From s In data.TinNhans Where s.RaoVatId = intId Select s).ToList
                        For Each o In j
                            data.TinNhans.DeleteObject(o)
                        Next

                        Dim w = (From z In data.TinDaLuus Where z.RaoVatID = intId Select z).ToList
                        For Each m In w
                            data.TinDaLuus.DeleteObject(m)
                        Next

                        data.SaveChanges()

                        Dim q = (From p In data.RaoVats Where p.RaovatId = intId Select p).FirstOrDefault
                        Try
                            'delete image
                            Dim DelPath = Server.MapPath("~/Uploads") & (q.ImagePreview.Replace("http://otosaithanh.com/Uploads", "").Replace(MainDomain & "Uploads", ""))
                            DeleteFileRaoVat(DelPath)

                            data.RaoVats.DeleteObject(q)
                            data.SaveChanges()
                            Insert_App_Log("Insert Rao Vat:" & txtTitle.Text.Trim & "", Function_Name.Raovat, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                            intCount += 1
                        Catch ex As Exception
                        End Try
                    End If
                Next
                If intCount > 0 Then
                    Excute_Javascript("Alertbox('Xóa dữ liệu thành công. " & intCount.ToString & " /" & intTotal.ToString & " record.');", Me.Page, True)
                Else
                    Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
                End If
            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                Excute_Javascript("Alertbox('Xóa thất bại.');", Me.Page, True)
            End Try
        End Using
        BindToGrid()
    End Sub
    Protected Sub grdShow_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdShow.RowDataBound
        If e.Row.RowIndex >= 0 Then
            Dim lblSTT As Label = CType(e.Row.FindControl("lblSTT"), Label)
            lblSTT.Text = CInt(drpPage_Size.SelectedValue) * (CInt(hidCur_Page.Value) - 1).ToString + e.Row.RowIndex + 1
            Dim lnkbtnDelete As LinkButton = CType(e.Row.FindControl("lnkbtnDelete"), LinkButton)
            lnkbtnDelete.Attributes.Add("onclick", "return ComfirmDialog('" + drpMessage.Items(0).Text + "', 0,'" + lnkbtnDelete.ClientID + "','" + e.Row.RowIndex.ToString + "',1);")
            Dim hplEdit As HyperLink = CType(e.Row.FindControl("hplEdit"), HyperLink)
            hplEdit.NavigateUrl = "../../Page/Raovat/Edit.aspx?RaovatId=" & grdShow.DataKeys(e.Row.RowIndex)("RaovatId").ToString
            Dim hplTitle As HyperLink = CType(e.Row.FindControl("hplTitle"), HyperLink)
            hplTitle.NavigateUrl = "../../Page/Raovat/Detail.aspx?RaovatId=" & grdShow.DataKeys(e.Row.RowIndex)("RaovatId").ToString
            hplTitle.Text = grdShow.DataKeys(e.Row.RowIndex)("Title").ToString
        End If
    End Sub
    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        BindToGrid(1, txtTitle.Text.Trim, ddlType.SelectedValue, StringToDate(txtCreatedFrom.Text.Trim, "dd/mm/yyyy"), StringToDate(IIf(String.IsNullOrEmpty(txtCreatedTo.Text.Trim) = True, "31/12/3999", txtCreatedTo.Text.Trim), "dd/mm/yyyy"), txtCreatorid.Text.Trim, _
                CInt(chkIsselloff.SelectedValue), CInt(chkIshot.SelectedValue), ddlStatus.SelectedValue, _
                StringToDate(txtPublisheddateFrom.Text.Trim, "dd/mm/yyyy"), _
                 StringToDate(IIf(String.IsNullOrEmpty(txtPublisheddateTo.Text.Trim) = True, "31/12/3999", txtPublisheddateTo.Text.Trim), "dd/mm/yyyy"))

    End Sub

    Protected Sub btnReset_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReset.Click

        txtTitle.Text = ""
        txtCreatedFrom.Text = ""
        txtCreatedTo.Text = ""
        txtCreatorid.Text = ""
        ddlStore.SelectedValue = -1
        chkIsselloff.SelectedValue = -1
        chkIshot.SelectedValue = -1
        ddlStatus.SelectedValue = -1
        txtPublisheddateFrom.Text = ""
        txtPublisheddateTo.Text = ""
        drpPage_Size.SelectedIndex = -1
        ddlType.SelectedValue = -1
        BindToGrid(1)
    End Sub
    Protected Sub drpPage_Size_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles drpPage_Size.SelectedIndexChanged
        Dim arrSearch() As String
        arrSearch = ViewState("search")
        BindToGrid(1, arrSearch(1).ToString, CInt(arrSearch(2).ToString), StringToDate(arrSearch(3).ToString, "dd/mm/yyyy"), arrSearch(4), arrSearch(5).ToString, CInt(arrSearch(6).ToString), CInt(arrSearch(7).ToString), CInt(arrSearch(8).ToString), StringToDate(arrSearch(9).ToString, "dd/mm/yyyy"), arrSearch(10))

    End Sub

    Protected Sub DeleteFileRaoVat(ByVal DelPathFile As String)

        Dim arrImageHot(,) As Integer = {{84, 84}, {120, 120}, {90, 60}, {320, 300}, {800, 600}, {420, 300}}
        Dim strFileName As String = DelPathFile.Split("/")(DelPathFile.Split("/").Length - 1)
        Dim DelPath As String = DelPathFile.Replace(strFileName, "")
        'delete file goc
        If (System.IO.File.Exists(DelPathFile)) Then
            File.Delete(DelPathFile)
        End If
        'delete thumbnail
        For j As Integer = 0 To UBound(arrImageHot)
            Dim strNewFile = arrImageHot(j, 0).ToString & "-" & arrImageHot(j, 1) & "-" & strFileName
            Dim DelPathReal = DelPath & strNewFile
            If (System.IO.File.Exists(DelPathReal)) Then
                File.Delete(DelPathReal)
            End If

        Next



    End Sub

#End Region


End Class
